package com.gin.kotlin.no_gay_alliance.fragment.pm

import android.os.Bundle
import android.view.View
import com.gin.kotlin.no_gay_alliance.activity.pm.PrivateMessageReplyActivity
import com.gin.kotlin.no_gay_alliance.argument.PrivateMessageReplyArgument
import com.gin.kotlin.no_gay_alliance.base.AbstractBindingFragment
import com.gin.kotlin.no_gay_alliance.callback.RCallback
import com.gin.kotlin.no_gay_alliance.databinding.FragmentPrivateMessagePageAbstractBinding
import com.gin.kotlin.no_gay_alliance.enums.HandlerMessageWhat
import com.gin.kotlin.no_gay_alliance.provider.ngaphp.PrivateMessageReplyProvider
import com.gin.nga.response.message.PriMsgReplyData

/**
 * 一页私信回复，处理请求逻辑，渲染部分待实现
 * @param T :ViewBinding
 */
abstract class AbstractPrivateMessageReplyPageFragment : AbstractBindingFragment<FragmentPrivateMessagePageAbstractBinding>(),
    RCallback<PriMsgReplyData, PrivateMessageReplyArgument> {
    private lateinit var argument: PrivateMessageReplyArgument

    override fun onCreateView() {
        initRenderComponent(b ?: return)
        b?.swipeRefreshLayout?.setOnRefreshListener { refresh() }
        request()
    }

    override fun handleArguments(bundle: Bundle) {
        this.argument = parseBundle(bundle, PrivateMessageReplyArgument::class.java.simpleName, PrivateMessageReplyArgument::class.java)
    }

    override fun onResume() {
        super.onResume()
        (requireActivity() as? PrivateMessageReplyActivity)?.also { it.currentFragment = this }

        // 发送消息更新当前页
        findParentHandler().sendMessage(HandlerMessageWhat.PAGE_UPDATED, this.argument.page!!)
    }

    fun refresh() {
        request(true)
    }

    private fun request(ignoreCache: Boolean = false) {
        b?.tvWarning?.visibility = View.GONE
        b?.swipeRefreshLayout?.isRefreshing = true
        PrivateMessageReplyProvider.getInstance().enqueue(argument, ignoreCache = ignoreCache, callback = this)
    }

    override fun onSuccess(data: PriMsgReplyData, ignoreCache: Boolean) {
        b?.swipeRefreshLayout?.isRefreshing = false
        // 更新当前页信息
        if (data.hasNext == true) findParentHandler().sendMessage(HandlerMessageWhat.PAGE_UPDATED, data.page ?: 0, data.page?.plus(1) ?: 1)

        // 更新参与用户信息
        data.getUsers()?.also { handler?.sendMessage(HandlerMessageWhat.PRIVATE_MESSAGE_USER, it) }

        onSuccess(data)
    }

    override fun onError(errorMessage: String) {
        b?.swipeRefreshLayout?.isRefreshing = false
        b?.tvWarning?.visibility = View.VISIBLE
        b?.tvWarning?.text = errorMessage
        onError()
    }

    /**
     * 请求错误时的回调，如清空或隐藏渲染组件
     */
    abstract fun onError()

    /**
     * 初始化渲染组件
     * @param binding FragmentPrivateMessagePageAbstractBinding
     */
    abstract fun initRenderComponent(binding: FragmentPrivateMessagePageAbstractBinding)

    /**
     * 请求成功回调，执行渲染
     * @param data PriMsgReplyData
     */
    abstract fun onSuccess(data: PriMsgReplyData)
}
